package archimede;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Scanner;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;

import net.miginfocom.swing.MigLayout;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;


public class tableM extends JPanel {
   private JTextField height = new JTextField() {
      @Override
      protected void paintComponent(Graphics g) {
         if (!isOpaque()) {
            int w = getWidth();
            int h = getHeight();
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(UIManager.getColor("TextField.background"));
            g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
            g2.setColor(Color.BLACK);
            g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
            g2.dispose();
         }
         super.paintComponent(g);
      }
   };
   private JTextField depth = new JTextField() {
      @Override
      protected void paintComponent(Graphics g) {
         if (!isOpaque()) {
            int w = getWidth();
            int h = getHeight();
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(UIManager.getColor("TextField.background"));
            g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
            g2.setColor(Color.BLACK);
            g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
            g2.dispose();
         }
         super.paintComponent(g);
      }
   };
   private JTextField humidity = new JTextField("") {
      @Override
      protected void paintComponent(Graphics g) {
         if (!isOpaque()) {
            int w = getWidth();
            int h = getHeight();
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(UIManager.getColor("TextField.background"));
            g2.fillRoundRect(0, 0, w - 2, h - 2, 10, 10);
            g2.setColor(Color.BLACK);
            g2.drawRoundRect(0, 0, w - 2, h - 2, 10, 10);
            g2.dispose();
         }
         super.paintComponent(g);
      }
   };
   private String[] matItem = { "", "intonaco", "fuga", "C.A.", "poroton", "blocchi cemento", "bi-mattoni", "mattoni", "fuga-mattone",
         "fuga-blocco cemento", "tramezza in laterizio", "tufo", "laterizio", "altro" };
   private JButton delRilevazione = new JButton(new ImageIcon(ClassLoader.getSystemResource("delete.png")));
   private JComboBox material = new JComboBox(matItem);
   private boolean modifyMaterial = false;
   private JTextField otherMaterial = new JTextField();

   private String[] valItem = { "", "fuori terra", "contro terra", "muro intermedio" };
   private JComboBox value = new JComboBox(valItem);
   private JRadioButton critico = new JRadioButton();
   private JRadioButton medio = new JRadioButton();
   private JRadioButton naturale = new JRadioButton();

   private int count;
   private JLabel name = new JLabel();
   private ObjM m;

   public tableM(StartingWindow st, final int counts, final ObjM m) {
      super();
      this.count = counts;
      this.m=m;
      // System.out.println("table " + count);
      delRilevazione.setBorder(null);
      delRilevazione.setContentAreaFilled(false);
      delRilevazione.setRolloverEnabled(true);
      delRilevazione.setRolloverIcon(new ImageIcon(ClassLoader.getSystemResource("bdelete.png")));
      setLayout(new MigLayout());
      setOpaque(false);
      if (humidity.getText().equals(""))
         humidity.setEditable(true);
      else
         humidity.setEditable(false);
      height.setBorder((BorderFactory.createEmptyBorder(4, 8, 4, 8)));
      depth.setBorder((BorderFactory.createEmptyBorder(4, 8, 4, 8)));
      humidity.setBorder((BorderFactory.createEmptyBorder(4, 8, 4, 8)));
      height.setOpaque(false);
      depth.setOpaque(false);
      humidity.setOpaque(false);

      height.setPreferredSize(new Dimension(140, 20));
      depth.setPreferredSize(new Dimension(140, 20));
      humidity.setPreferredSize(new Dimension(70, 20));
      material.setPreferredSize(new Dimension(210, 20));
      value.setPreferredSize(new Dimension(210, 20));
      otherMaterial.setBorder(BorderFactory.createLineBorder(Color.GRAY));
      otherMaterial.setPreferredSize(new Dimension(210, 25));

      critico.setBackground(Color.RED);
      medio.setBackground(Color.YELLOW);
      naturale.setBackground(Color.GREEN);
      addAction();
      delRilevazione.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            int res = JOptionPane.showConfirmDialog(null, "Eliminare valori?", "Attenzione", 0);
            if (res == 0) {

               m.removeTabel(count);
            }
         }
      });

      JLabel space = new JLabel(" ");
      name.setText("" + (count + 1));

      add(name, "cell 0 0");
      add(delRilevazione, "cell 1 0");
      add(height, "cell 2 0 ");
      add(depth, "cell 3 0 ");
      add(humidity, "cell 4 0");
      add(critico, "cell 5 0");
      add(medio, "cell 6 0");
      add(naturale, "cell 7 0");
      add(material, "cell 9 0 , gapleft 5");
      add(value, "cell 10 0");
   }

   public void addAction() {
      material.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            if (((String) material.getSelectedItem()).equals("altro")) {
               remove(material);
               add(otherMaterial, "cell 9 0, gapleft 5");

               modifyMaterial = true;
               paintAll(getGraphics());
            }
         }
      });

      critico.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            medio.setSelected(false);
            naturale.setSelected(false);
         }
      });
      medio.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            naturale.setSelected(false);
            critico.setSelected(false);
         }
      });
      naturale.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            critico.setSelected(false);
            medio.setSelected(false);
         }
      });

      MouseAdapter ml1 = new MouseAdapter() {
         public void mousePressed(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1) {

               if (!humidity.getText().equals("")) {
                  int res = JOptionPane.showConfirmDialog(null, "Sovrascivere dati?", "Attenzione", 0);
                  if (res == 0) {

                     humidity.setEditable(true);
                  } else if (humidity.getText().equals(""))
                     humidity.setEditable(true);
                  else
                     humidity.setEditable(false);
               }
            }
         }
      };
      humidity.addMouseListener(ml1);

      MouseAdapter ml2 = new MouseAdapter() {
         public void mousePressed(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3) {
               remove(otherMaterial);
               material.setSelectedIndex(0);
               add(material, "cell 9 0, gapleft 5");
               modifyMaterial = false;

               paintAll(getGraphics());
            }
         }
      };
      otherMaterial.addMouseListener(ml2);

      MouseAdapter ml3 = new MouseAdapter() {
         public void mousePressed(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1) {

               if (humidity.getText().equals(""))
                  humidity.setEditable(true);
               else
                  humidity.setEditable(false);
            }
         }
      };
      addMouseListener(ml3);
      height.addMouseListener(ml3);
      depth.addMouseListener(ml3);
      material.addMouseListener(ml3);
      otherMaterial.addMouseListener(ml3);
      value.addMouseListener(ml3);
      ;

   }

   public void setCount(int counts) {
      // System.out.println("set : old-> " + count + " new-> " + counts);
      this.count = counts;
      name.setText("" + (counts + 1));
      paintAll(getGraphics());
   }

   public String print() {
      String print = "\n#";
      print = print + height.getText();
      print = print + "\n#" + depth.getText();
      print = print + "\n#" + humidity.getText();
      print = print + "\n#" + critico.isSelected();
      print = print + "\n#" + medio.isSelected();
      print = print + "\n#" + naturale.isSelected();
      if (modifyMaterial)
         print = print + "\n#" + otherMaterial.getText();
      else
         print = print + "\n#" + material.getSelectedIndex();
      print = print + "\n#" + value.getSelectedIndex();

      if (!critico.isSelected() && !medio.isSelected() && !naturale.isSelected())
         JOptionPane.showMessageDialog(null, "Nessun valore selezionato in M "  +m.getM()+"."+ name.getText());

      return print;

   }

   public void setElement(String data) {
      Scanner c = new Scanner(data);
      // System.out.println("[[[[[\n" + data);
      // c.nextLine();

      height.setText(c.nextLine());
      depth.setText(c.nextLine());
      humidity.setText(c.nextLine());
      if (c.nextLine().equals("true"))
         critico.setSelected(true);
      else
         critico.setSelected(false);
      if (c.nextLine().equals("true"))
         medio.setSelected(true);
      else
         medio.setSelected(false);
      if (c.nextLine().equals("true"))
         naturale.setSelected(true);
      else
         naturale.setSelected(false);

      String tmp = c.nextLine();
      try {
         material.setSelectedIndex(Integer.parseInt(tmp));
      } catch (NumberFormatException e) {
         otherMaterial.setText(tmp);
         remove(material);
         add(otherMaterial, "cell 9 0, gapleft 5");
         modifyMaterial = true;
         paintAll(getGraphics());
      }
      tmp = c.nextLine();
      try {
         value.setSelectedIndex(Integer.parseInt(tmp));
      } catch (NumberFormatException e) {
      }

   }

   public Document pdf(Document doc, int n, int v) {

      PdfPTable table = new PdfPTable(8);
      int[] size = { 25, 30, 30, 20, 10, 45, 60, 60 };
      try {
         table.setWidths(size);
         table.setWidthPercentage(100);
      } catch (DocumentException e1) {
         // TODO Auto-generated catch block
         e1.printStackTrace();
      }

      Phrase testo = new Phrase("M " + n + "." + v, FontFactory.getFont(FontFactory.TIMES, 11));
      PdfPCell cos = new PdfPCell(testo);
      cos.setHorizontalAlignment(Element.ALIGN_CENTER);
      cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cos.setFixedHeight(20);
      table.addCell(cos);

      testo = new Phrase(height.getText() + "  cm", FontFactory.getFont(FontFactory.TIMES, 11));
      cos = new PdfPCell(testo);
      cos.setHorizontalAlignment(Element.ALIGN_CENTER);
      cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cos.setFixedHeight(20);
      table.addCell(cos);

      testo = new Phrase(depth.getText() + "  cm", FontFactory.getFont(FontFactory.TIMES, 11));
      cos = new PdfPCell(testo);
      cos.setHorizontalAlignment(Element.ALIGN_CENTER);
      cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cos.setFixedHeight(20);
      table.addCell(cos);

      testo = new Phrase(humidity.getText() + " %", FontFactory.getFont(FontFactory.TIMES, 11));
      cos = new PdfPCell(testo);
      cos.setHorizontalAlignment(Element.ALIGN_CENTER);
      cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cos.setFixedHeight(20);
      table.addCell(cos);

      String value = "";

      try {
         com.itextpdf.text.Image img;
         if (critico.isSelected()) {
            value = "Critico";
            img = com.itextpdf.text.Image.getInstance(ClassLoader.getSystemResource("red.jpg"));
            img.scaleAbsolute(14, 14);
            cos = new PdfPCell(img);
            cos.setHorizontalAlignment(Element.ALIGN_CENTER);
            cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cos.disableBorderSide(PdfPCell.RIGHT);
            table.addCell(cos);
         } else if (medio.isSelected()) {
            value = "Poco critico";
            img = com.itextpdf.text.Image.getInstance(ClassLoader.getSystemResource("yellow.jpg"));
            img.scaleAbsolute(14, 14);
            cos = new PdfPCell(img);
            cos.setHorizontalAlignment(Element.ALIGN_CENTER);
            cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cos.disableBorderSide(PdfPCell.RIGHT);
            table.addCell(cos);
         } else if (naturale.isSelected()) {
            value = "Naturale";
            img = com.itextpdf.text.Image.getInstance(ClassLoader.getSystemResource("green.jpg"));
            img.scaleAbsolute(14, 14);
            cos = new PdfPCell(img);
            cos.setHorizontalAlignment(Element.ALIGN_CENTER);
            cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cos.disableBorderSide(PdfPCell.RIGHT);
            table.addCell(cos);
         } else {
            // null
            value = "NULL";
            img = com.itextpdf.text.Image.getInstance(ClassLoader.getSystemResource("grey.jpg"));
            img.scaleAbsolute(14, 14);
            cos = new PdfPCell(img);
            cos.setHorizontalAlignment(Element.ALIGN_CENTER);
            cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cos.disableBorderSide(PdfPCell.RIGHT);
            table.addCell(cos);
         }

      } catch (BadElementException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (MalformedURLException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

      testo = new Phrase(value, FontFactory.getFont(FontFactory.TIMES, 11));
      cos = new PdfPCell(testo);
      cos.setHorizontalAlignment(Element.ALIGN_LEFT);
      cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cos.disableBorderSide(PdfPCell.LEFT);
      cos.setFixedHeight(20);
      table.addCell(cos);

      if (modifyMaterial)
         testo = new Phrase(otherMaterial.getText(), FontFactory.getFont(FontFactory.TIMES, 11));
      else
         testo = new Phrase((String) material.getSelectedItem(), FontFactory.getFont(FontFactory.TIMES, 11));
      cos = new PdfPCell(testo);
      cos.setHorizontalAlignment(Element.ALIGN_CENTER);
      cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cos.setFixedHeight(20);
      table.addCell(cos);

      testo = new Phrase((String) this.value.getSelectedItem(), FontFactory.getFont(FontFactory.TIMES, 11));
      cos = new PdfPCell(testo);
      cos.setHorizontalAlignment(Element.ALIGN_CENTER);
      cos.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cos.setFixedHeight(20);
      table.addCell(cos);

      try {

         doc.add(table);
      } catch (DocumentException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

      return doc;
   }

}
